package org.ceteca.explica.server.warehouse;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.apache.log4j.Logger;
import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.ssl.RMISSLClientSocketFactory;
import org.ceteca.explica.core.ssl.RMISSLServerSocketFactory;
import org.ceteca.explica.core.util.LoggerFactory;
import org.ceteca.explica.core.warehouse.InterfaceWarehouse;
import org.ceteca.explica.core.warehouse.WarehouseManager;
import org.ceteca.explica.server.ServerContext;

public class WarehouseManagerBuilder {
	/**
	 * Initializes the warehouse manager remote object. Makes the registration and
	 * binding of the remote WarehouseManager service.  
	 */
	public static void initWarehouseManager() {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = InterfaceExplica.JNDI_WAREHOUSE_MANAGER_EXPORT_NAME;
            WarehouseManagerImpl manager = new WarehouseManagerImpl();
            
            UnicastRemoteObject.unexportObject(manager, true);
            System.out.println("WarehouseManager unexported");


            /**
             * Export the WarehouseManager object to listen in the assigned port
             */
            WarehouseManager stub =
                (WarehouseManager) UnicastRemoteObject.exportObject(manager, InterfaceExplica.RMI_WAREHOUSE_MANAGER_EXPORT_PORT, 
                		new RMISSLClientSocketFactory(),
               		 	new RMISSLServerSocketFactory());
            
            System.out.println("WarehouseManager exported");

            /*
    	     * Create a registry and bind stub in registry.
    	     */
//    	    LocateRegistry.createRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    Registry registry = LocateRegistry.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    
            System.out.println("Registry located");
            registry.rebind(name, stub);
            System.out.println("WarehouseManager bound");
        } catch (Exception e) {
            System.err.println("WarehouseManager exception:");
            e.printStackTrace();
        }
        
        // Init the logger service
		System.out.println("LOGGING CONFIGURATION PATH= " + ServerContext.getInstance().getClass().getResource(InterfaceWarehouse.WAREHOUSE_LOG_CONFIG_FILE).getPath());
		LoggerFactory.initLogger(
				InterfaceExplica.EXPLICA_LOG_DIR,
				ServerContext.getInstance().getClass().getResourceAsStream(InterfaceWarehouse.WAREHOUSE_LOG_CONFIG_FILE));
	
	}
	
	public static final Logger getLogger() {
		return ServerContext.getInstance().getLogger(InterfaceWarehouse.WAREHOUSE_LOG_CATEGORY);
	}
}
